package _4lists.src.SinglyLinkedList;

import java.io.PrintStream;
import java.util.Iterator;
import java.util.Objects;
import java.util.function.Consumer;

public class SinglyLinkedList_old {
    //创建一个节点类
    private static class Node {
        int value;
        Node next;

        public Node(int value, Node next) {
            this.value = value;
            this.next = next;
        }
    }
    private Node head = null;

    public SinglyLinkedList_old() {
    }

    public void addFirst(int value) {
        this.head = new Node(value, this.head);
    }

    public void loop1(Consumer<Integer> consumer) {
        for(Node p = this.head; p != null; p = p.next) {
            consumer.accept(p.value);
        }

    }

    public void loop2(Consumer<Integer> consumer) {
        for(Node p = this.head; p != null; p = p.next) {
            consumer.accept(p.value);
        }

    }

    public Iterator<Integer> iterator() {
        return new Iterator<Integer>() {
            Node p;

            {
                this.p = SinglyLinkedList_old.this.head;
            }

            public boolean hasNext() {
                return this.p != null;
            }

            public Integer next() {
                int v = this.p.value;
                this.p = this.p.next;
                return v;
            }
        };
    }

    public Node findLast() {
        if (this.head == null) {
            return null;
        } else {
            Node p;
            for(p = this.head; p.next != null; p = p.next) {
            }

            return p;
        }
    }

    public void addLast(int value) {
        Node Last = this.findLast();
        if (Last == null) {
            this.addFirst(value);
        } else {
            Last.next = new Node(value, (Node)null);
        }
    }

    public static void main(String[] args) {
        SinglyLinkedList_old singlyLinkedList = new SinglyLinkedList_old();
        singlyLinkedList.addFirst(1);
        singlyLinkedList.addFirst(2);
        singlyLinkedList.addFirst(3);
        singlyLinkedList.addFirst(4);
        singlyLinkedList.addLast(5);
        PrintStream var10001 = System.out;
        Objects.requireNonNull(var10001);
        singlyLinkedList.loop1(var10001::println);
    }


}
